package io.github.ramerf.wind.core.handler.typehandler;

import io.github.ramerf.wind.core.executor.DataAccessException;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;

/**
 * {@literal java:Long[] <=> jdbc:逗号分割的字符串}.
 *
 * @since 2024.04.20
 * @author ramer
 */
public class LongArrayToCommaTypeHandler implements ITypeHandler<Collection<Long>, String> {
  private static final Pattern COMMA = Pattern.compile(",");

  @Override
  public Object convertToJdbc(
      Collection<Long> javaVal, final Field field, @Nonnull final PreparedStatement ps) {
    if (javaVal == null) {
      return null;
    }
    try {
      final Connection connection = ps.getConnection();
      return javaVal.stream().map(String::valueOf).collect(Collectors.joining(",", "", ","));
    } catch (SQLException e) {
      throw new DataAccessException(e);
    }
  }

  @Override
  public Collection<Long> convertFromJdbc(
      final String jdbcVal, final Object defaultValue, final Field field) {
    if (defaultValue == null) {
      return List.class.isAssignableFrom(field.getType())
          ? (jdbcVal == null
              ? new ArrayList<>()
              : COMMA.splitAsStream(jdbcVal).map(Long::parseLong).collect(Collectors.toList()))
          : (jdbcVal == null
              ? new HashSet<>()
              : COMMA.splitAsStream(jdbcVal).map(Long::parseLong).collect(Collectors.toSet()));
    }
    @SuppressWarnings("unchecked")
    final Collection<Long> initial = (Collection<Long>) defaultValue;
    initial.clear();
    initial.addAll(COMMA.splitAsStream(jdbcVal).map(Long::parseLong).collect(Collectors.toList()));
    return initial;
  }
}
